<template>
  <div class="form-function-modal-page">
    <je-modal
      v-model:visible="isShow"
      title="功能配置"
      :footer="null"
      width="97%"
      height="97%"
      class="default-modal"
      @close="onButton"
    >
      <!-- 头部tab数据显示 -->
      <je-tabs
        v-model:activeKey="activeKey"
        tab-position="top"
        class="header-tabs"
        :class="[childActiveKey == 'listFieldConfig' ? 'listFieldConfigClass' : '']"
        style="height: 100%; border-radius: 6px"
      >
        <je-tab-pane v-for="item in tabsData" v-show="activeKey == item.value" :key="item.value">
          <template #tab>
            <span>
              <i :class="item.icon"></i>
              {{ item.label }}
            </span>
          </template>
          <!-- 底部有tab显示的数据 -->
          <je-tabs
            v-if="item.childTabData && item.childTabData.length"
            v-model:activeKey="childActiveKey"
            tab-position="bottom"
          >
            <je-tab-pane
              v-for="childTabItem in item.childTabData"
              v-show="childActiveKey == childTabItem.value"
              :key="childTabItem.value"
            >
              <template #tab>
                <div @click.stop="clickTab(childTabItem.value)">{{ childTabItem.label }}</div>
              </template>
              <component
                :is="childTabItem.compontent"
                :ref="childRef"
                :key="`${parentActiveKey}${recordData.JE_CORE_FUNCINFO_ID}`"
                :record-data="recordData"
                :action-object="actionObject"
                class="component-height"
                @changeRecord="changeRecord"
                @passActionValue="passActionValue"
              ></component>
            </je-tab-pane>
            <span class="clean-cache">
              <je-button type="link" @click="cleanCache">清除功能缓存</je-button>
            </span>
          </je-tabs>
          <component :is="item.compontent" v-else :record-data="recordData"></component>
        </je-tab-pane>
      </je-tabs>
    </je-modal>
  </div>
</template>

<script>
  import { ref, defineComponent, onMounted, watch, reactive } from 'vue';
  import { FUNCTION_TABS_DATA } from '@/helper/constant';
  import { FUNCTION_COMPONTENT } from '@/helper/compontents';
  import { Modal, Tabs, Button } from '@jecloud/ui';
  import { cleanCache } from '@/helper/function';
  import { useProvideFunction } from './context';

  export default defineComponent({
    name: 'FormFunctionModal',
    components: {
      JeModal: Modal,
      JeTabs: Tabs,
      JeButton: Button,
      JeTabPane: Tabs.TabPane,
      ...FUNCTION_COMPONTENT,
    },
    props: {
      visble: {
        type: Boolean,
        default: false,
      },
      record: {
        type: Object,
        default: () => {
          return {};
        },
      },
      parentActiveKey: {
        type: String,
        default: 'function',
      },
      childActiveType: {
        type: String,
        default: 'functionBase',
      },
    },
    emits: ['refreshChildData', 'changeModal'],
    setup(props, { emit }) {
      const isShow = ref(props.visble);
      // 父组件传过来的node数据
      const recordData = ref(props.record);
      console.log('-----', recordData.value);
      const activeKey = ref(props.parentActiveKey);
      const childActiveKey = ref(props.childActiveType);
      const actionObject = ref({});
      const itemRefs = [];
      const childRef = (el) => {
        if (el) {
          itemRefs.push(el);
        }
      };

      const methods = {
        // 将列表和表单的事件的闪电状态返给列表和表单
        passActionValue(obj) {
          actionObject.value = Object.assign(actionObject.value, obj);
        },
        changeRecord(data) {
          recordData.value.JE_CORE_RESOURCETABLE_ID = data;
        },
        // 点击右上角的关闭按钮
        onButton() {
          isShow.value = false;
          emit('changeModal', isShow.value);
        },
        clickTab(value) {
          if (childActiveKey.value === 'formDesign') {
            let findIndex = itemRefs.findIndex(
              (item) => item.name === 'formDesign' && item.info.data,
            );
            let component = itemRefs[findIndex];

            // 如果没有数据更改就不弹出提示
            if (JSON.stringify(component.info.data) == JSON.stringify(component.info.defaultData)) {
              childActiveKey.value = value;
              return false;
            }

            // 离开表单界面设计
            Modal.dialog({
              content: '数据有改动，未保存，确定离开吗?',
              buttons: [
                {
                  text: '确定离开',
                  type: 'primary',
                  closable: false,
                  handler: ({ button, $modal }) => {
                    $modal.close();
                    component.getData();
                    // 因为 JSON.stringify 会忽略属性值为 undefined 的属性，使用下面的代码保存属性值为 undefined 的属性
                    // component.info.data = JSON.parse(
                    //   JSON.stringify(component.info.data, (key, value) =>
                    //     typeof value === 'undefined' ? '' : value,
                    //   ),
                    // );

                    // component.info.defaultData = JSON.parse(
                    //   JSON.stringify(component.info.data, (key, value) =>
                    //     typeof value === 'undefined' ? '' : value,
                    //   ),
                    // );

                    childActiveKey.value = value;
                  },
                },
                {
                  text: '保存离开',
                  type: 'primary',
                  closable: false,
                  handler: async ({ button, $modal }) => {
                    button.loading = true;

                    let result = await component.handleSubmit();
                    button.loading = false;
                    if (result) {
                      $modal.close();
                      childActiveKey.value = value;
                    }
                  },
                },
                {
                  text: '取消',
                },
              ],
            });
          } else if (childActiveKey.value === 'formFieldConfig') {
            let findIndex = itemRefs.findIndex(
              (item) => item.name === 'formFieldConfig' && item.xTable,
            );
            let component = itemRefs[findIndex];

            // 如果没有数据更改就不弹出提示
            if (component.xTable.getUpdateRecords().length === 0) {
              childActiveKey.value = value;
              return false;
            }

            // 离开表单字段配置
            Modal.dialog({
              content: '数据有改动，未保存，确定离开吗?',
              buttons: [
                {
                  text: '确定离开',
                  type: 'primary',
                  closable: false,
                  handler: ({ button, $modal }) => {
                    component.xTable.$plugin.reloadData(component.tableData);

                    $modal.close();
                    childActiveKey.value = value;
                  },
                },
                {
                  text: '保存离开',
                  type: 'primary',
                  closable: false,
                  handler: async ({ button, $modal }) => {
                    button.loading = true;
                    let result = await component.formDataSave();

                    button.loading = false;

                    if (result) {
                      $modal.close();
                      childActiveKey.value = value;
                    }
                  },
                },
                {
                  text: '取消',
                },
              ],
            });
          } else {
            childActiveKey.value = value;
          }
        },
      };
      // 当顶部的tabs切换的时候，初始底部选中的childActiveKey
      watch(
        () => activeKey.value,
        (newValue) => {
          if (newValue == 'function') {
            childActiveKey.value = 'functionBase';
          } else if (newValue == 'list') {
            childActiveKey.value = 'listFieldConfig';
          } else if (newValue == 'form') {
            childActiveKey.value = 'formDesign';
          } else {
            childActiveKey.value = '';
          }
        },
      );

      onMounted(() => {});

      // 功能对象
      useProvideFunction({
        formState: reactive({}),
      });

      return {
        isShow,
        tabsData: ref(FUNCTION_TABS_DATA),
        activeKey,
        ...methods,
        childActiveKey,
        recordData,
        cleanCache,
        actionObject,
        childRef,
      };
    },
  });
</script>
<style lang="less" scoped>
  .form-function-modal-page {
    width: 100%;
    height: 100%;
    overflow: hidden;
    // position: relative;
  }
</style>
<style lang="less">
  .component-height {
    height: 100%;
    overflow: hidden;
  }
  .default-modal {
    > .je-modal--header {
      height: 50px !important;
      line-height: 50px !important;
    }
  }

  .default-modal {
    .header-tabs,
    .ant-tabs,
    .ant-tabs-content {
      height: 100%;
      overflow: hidden;
    }
    // .ant-tabs-nav-wrap > .ant-tabs-nav-list > .ant-tabs-tab-active {
    //   background: #ffffff;
    // }
    .ant-tabs-top > .ant-tabs-nav,
    .ant-tabs-bottom > .ant-tabs-nav,
    .ant-tabs-top > div > .ant-tabs-nav,
    .ant-tabs-bottom > div > .ant-tabs-nav {
      margin: 0 !important;

      height: 40px;
      line-height: 40px;
    }
    .ant-tabs-top > div > .ant-tabs-nav,
    .ant-tabs-top > .ant-tabs-nav {
      padding: 0 16px !important;
    }
    .ant-tabs-bottom {
      .ant-tabs-nav-list {
        .ant-tabs-tab {
          padding: 0 16px;
        }
        .ant-tabs-tab + .ant-tabs-tab {
          margin: 0 0 0 0 !important;
        }
        .ant-tabs-tab.ant-tabs-tab-active {
          background: @primary-color;
          .ant-tabs-tab-btn {
            color: #ffffff;
          }
        }
        .ant-tabs-ink-bar.ant-tabs-ink-bar-animated {
          height: 0px;
        }
      }
    }
    .ant-tabs-content-holder {
      overflow: hidden;
    }
    > .je-modal--body {
      padding: 0px !important;
      // 上边框
      // border-top: 1px solid #d9d9d9;
    }
    .listFieldConfigClass {
      .ant-tabs-nav::before {
        border-bottom: 0px solid #fff !important;
      }
    }
  }

  // 刷新功能缓存
  .clean-cache {
    position: absolute;
    right: 0;
    bottom: 3px;
  }
</style>
